package com.ai.scheduled;

import com.ai.common.constant.OpcConstant;
import com.ai.entity.made.OpcServerInfo;
import com.ai.service.made.IOpcNodeInfoService;
import com.ai.service.made.IOpcServerInfoService;
import com.google.common.collect.ImmutableList;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.milo.opcua.sdk.client.api.UaClient;
import org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem;
import org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.concurrent.ExecutionException;

/**
 * @Author jiaok
 * @Date 2024-11-19 15:35
 */
@Component
@Slf4j
public class OpcDetectJob {


    @Resource
    private IOpcServerInfoService iOpcServerInfoService;

    @Resource
    private IOpcNodeInfoService iOpcNodeInfoService;

    @Scheduled(cron = "0 */3 * * * ?")
    public void doTask(){
        log.info("========================    开始检测opc节点的监控状态    ========================");
        if (!CollectionUtils.isEmpty(OpcConstant.OPC_SERVER_ID_CLIENT_MAP)){
            for (String opcServerId : OpcConstant.OPC_SERVER_ID_CLIENT_MAP.keySet()) {
                UaClient uaClient = OpcConstant.OPC_SERVER_ID_CLIENT_MAP.get(opcServerId);
                OpcServerInfo opcServerInfo = iOpcServerInfoService.getById(opcServerId);
//                try {
                    ImmutableList<UaSubscription> subscriptions = uaClient.getSubscriptionManager().getSubscriptions();
                    if (subscriptions.size() == 0){
                            log.info("==============  {} 监控连接为空，开始重新建立监控连接 ： ===============",opcServerInfo.getOpcServerName());
                            iOpcServerInfoService.rebuildOpcSubscribe(opcServerId,uaClient);
                    }else {
                        log.info("==============  {} 监控连接正常  ===============",opcServerInfo.getOpcServerName());
                    }
            }

        }else {
            log.info("===========================  当前无需检测opc客户端连接状态  ===========================");
        }
    }
}
